package mt.demo.web.controller.news;

import mt.demo.domain.NewsDomain;
import mt.demo.service.news.NewsService;
import mt.demo.web.comm.YomsBase64Image;
import mt.demo.web.comm.resolverArg.WatArrayParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Created by watson on 2015/9/24.
 */
@Controller
@RequestMapping(value = "/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    //查询页面
    @RequestMapping(value = "newsFind.html", method = RequestMethod.GET)
    public ModelAndView getNewsDomain(NewsDomain newsDomain) {
        List<NewsDomain> newsDomains = newsService.getDomain(newsDomain);
        ModelAndView mav = new ModelAndView("news/newsFind");
        mav.addObject("news", newsDomains);
        return mav;
    }

    //传统方式保存图片
    @RequestMapping(value = "savePicture.html",method = RequestMethod.POST)
    @ResponseBody
    public void upload(MultipartFile file){
        if (file!=null){
            newsService.SavePicture(file);
        }
    }

    //访问创建页面
    @RequestMapping(value = "newsCreate.html", method = RequestMethod.GET)
    public String AddDomain() {
        return "news/newsCreate";
    }

    //创建新闻
    @RequestMapping(value = "newsCreate.html", method = RequestMethod.POST)
    public String AddDomain(NewsDomain newsDomain) {
//        String content=newsDomain.getNewsContent();
//        newsDomain.setNewsContent("");
        newsService.CreateDomain(newsDomain);
        //将图片分离出来重新编译
//        newsDomain.setNewsContent(content);
//        recompileImg(newsDomain);
        return "news/newsCreate";
    }

    //删除新闻,不需要访问页面，直接post传进参数删除
    @RequestMapping(value = "newsDelete.html", method = RequestMethod.POST)
    //加responsebody应前端AjAX参数请求，
    @ResponseBody
    public void DelNews(@WatArrayParam List<Integer> ids) {
        if (ids != null) {
            //多个id传进来时，通过for循环遍历删除
            for (int id : ids) {
                newsService.DelDomain(id);
            }
        }
    }

    //重新编译
    public void recompileImg(NewsDomain newsDomain) {
        if (newsDomain.getNewsContent() != null) {
            newsDomain.setNewsContent(YomsBase64Image.recompileImgSrc(
                    newsDomain.getNewsContent(),
                    newsDomain.getNewsId(), "news/content").getValue());
        } else {
            newsDomain.setNewsContent("");
        }
    }


}
